/**
 * Created by zhoulin on 2019/4/3.
 */
var interval = [];
var app = new Vue({
    el: '#app',
    data: {
        permissions:['ubusiness:add','ubusiness:update'],//本页权限数组
        deptPerms:false,
        roles:false,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200)

            return ;
        }
        that.getDeptPerms();
        that.getRoles();
        if(!empty(aGET.id)){
            that.init();
        }

    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //解决修改时候数据不及时更新问题
        init:function () {
            var that = this;
            if(Boolean(that.roles) && Boolean(that.deptPerms)){
                for (var itme in interval){
                    window.clearInterval(interval[itme]);
                }
                that.getInfoById(aGET.id);
            }else {
                interval.push(
                    window.setInterval(function () {
                        that.init();
                    },1000))
            }
        },
        getInfoById:function (id) {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysBusiness_getInfoById+id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            var list = response.data
                            for (var item in list) {
                                if ('status' == item || 'sysDeptPermissions'== item || 'sysBusinessRoles'== item) {
                                    continue;
                                }
                                $("#Form input[name='"+item+"']").val(list[item]);

                            }

                            $("#Form select[name='status']").val(list['status']);

                            for (var item in list["sysDeptPermissions"]){
                                $("#deptPerms input[name='deptPerm'][value='" + list["sysDeptPermissions"][item].deptId + "']").iCheck('check');
                            }

                            for (var item in list["sysBusinessRoles"]){
                                $("#roles input[name='role'][value='" + list["sysBusinessRoles"][item].rid + "']").iCheck('check');
                            }

                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        //获取当前机构二级部门（校区）
        getDeptPerms:function () {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysDepartment_secondList)
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                        var html = "";
                        for (var item in response.list) {
                            html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="deptPerm" value="'+response.list[item].id+'"> '+response.list[item].name+'</label>'
                        }

                        $("#Form #deptPerms").append(html);
                        $("#deptPerms .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                        that.deptPerms = true;
                    }else {
                        layer.msg(response.msg, {time: 1500, icon:5});
                    }
                })
        },
        //获取当前机构角色
        getRoles:function () {
            var that = this;
            Get(that,_HOST+_API.business_manage_sysRole_getAllRole)
                .then(function (response) {
                    // 响应成功回调
                    if(response){
                        var html = "";
                        for (var item in response.list) {
                            html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="role" value="'+response.list[item].id+'"> '+response.list[item].name+'</label>'
                        }

                        $("#Form #roles").append(html);
                        $("#roles .i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});
                        that.roles = true;
                    }else {
                        layer.msg(response.msg, {time: 1500, icon:5});
                    }
                })
        },
        //
        add:function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            //console.log(param)
            var sysDeptPermissions = [];
            $("#deptPerms input[name='deptPerm']:checked").each(function () {
                sysDeptPermissions.push({"deptId":$(this).val()})
            })
            var sysBusinessRoles = [];
            $("#roles input[name='role']:checked").each(function () {
                sysBusinessRoles.push({"rid":$(this).val()})
            })
            param.sysDeptPermissions = sysDeptPermissions;
            param.sysBusinessRoles = sysBusinessRoles;
            Post(that,_HOST+_API.business_manage_sysBusiness_add,param,true,that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        update:function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            //console.log(param)
            var sysDeptPermissions = [];
            $("#deptPerms input[name='deptPerm']:checked").each(function () {
                sysDeptPermissions.push({"deptId":$(this).val(),"companyId":param.companyId,"bid":param.id})
            })
            var sysBusinessRoles = [];
            $("#roles input[name='role']:checked").each(function () {
                sysBusinessRoles.push({"rid":$(this).val(),"bid":param.id})
            })
            param.sysDeptPermissions = sysDeptPermissions;
            param.sysBusinessRoles = sysBusinessRoles;
            Put(that,_HOST+_API.business_manage_sysBusiness_update,param,true,that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        }
    },
})

$('#Form').data('bootstrapValidator', null);
Validator();
function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            username: {
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '用户名长度最多50个字符'
                    },
                }
            },
            nickname: {
                validators: {
                    notEmpty: {
                        message: '昵称不能为空'
                    },
                    stringLength: {
                        max: 1000,
                        message: '昵称长度最多1000个字符'
                    },
                }
            },
            wxTel: {
                validators: {
                    notEmpty:{
                        message:'微信绑定手机号不能为空'
                    },
                    phone:{
                        message:'请输入正确的电话号码',
                        country: 'CN'
                    },
                    stringLength: {
                        max: 15,
                        message: '电话号码长度最多15个字符'
                    }
                }
            },
            tel: {
                validators: {
                    notEmpty:{
                        message:'常用号码不能为空'
                    },
                    phone:{
                        message:'请输入正确的电话号码',
                        country: 'CN'
                    },
                    stringLength: {
                        max: 15,
                        message: '电话号码长度最多15个字符'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: '邮箱不能为空'
                    },
                    emailAddress: {
                        message: '请输入有效的邮箱'
                    }
                }
            },
            password: {
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: '密码长度在6到30之间'
                    }
                }
            },
            confirmPassword: {
                validators: {
                    notEmpty: {
                        message: '确认密码不能为空'
                    },
                    identical: {
                        field: 'password',
                        message: '两次密码不相同'
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if(empty(aGET.id)){
            app.add();
        }else {
            app.update();
        }
    });
}